
import mode from "../../utils/mode.js"
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showOK:false,
    temIds:['Wzq0Q8OpleP_KgHNxStTKJ6-8NdvRvqgJnioZ01w7bg'],
    integral_id:'',
    testGoodId:'',   //试用装id
    testGood:null,  //试用装详情
    isTest:0,     //是否是试用装
    goodType: '',
    couponId: '',
    couponInfo: {},     //优惠券详情---优惠券信息
    isRequest: false,
    VIPLevel: 1,
    userlevel: '',
    goodsNum: 1,
    goodsDetail: {},    //积分--商品详情
    userMessage: {},
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad (options) { 
    let that = this
    let info = wx.getStorageSync('uinfo')
    this.setData({
      goodType: options.type || '',
      user_id: info.user.id,
      id: info.user.id,
      isTest:options.is_test||0,
    })
    if(options && options.is_test){    //领取试用装
      await that.getGoodInfo(options.goodId)
    }else if (options && options.id && options.type) {   //积分产品详情
      await that.getJifenGood(options.type, options.id)
    } else {
      await that.getCoupons(options.couponsId)     //我的优惠券使用详情
    }

  },
  async getGoodInfo (id) {    //获取试用装详情
    wx.showLoading({
      title: '请求中',
    })
    var that = this
    await wx.$api.goodsGetInfo({
        goods_id: id
      }).then(res=>{
        if (res.code == 1) {
          wx.setNavigationBarTitle({
            title: res.data.goods_name,
          })
          that.setData({
            testGoodId: id,
            testGood: res.data
          })
        } else {
          wx.showToast({
            title: res.msg,
          })
        }
    })
    wx.hideLoading()
  },
  toGetTest(){   //领取试用装
    let that = this
    if(that.data.userMessage&&that.data.userMessage.test_goods>0){
      wx.showToast({ title: '用户不可重复领取体验装！', icon: 'none' })
    }else if(that.data.userMessage&&that.data.userMessage.is_member==1){
      wx.navigateTo({
        url: '/pages/settlement/settlement?is_test=1&testGoodId=' + that.data.testGoodId
      })
    }else{ 
      wx.navigateTo({
        url: '/pages/register/register'
      })
    }
    
  },
  async getCoupons (id) {    //优惠券兑换商品详情
    wx.showLoading({
      title: '请求中',
    })
    var that = this
    await wx.$api.getCouponInfo({
        coupon_user_id: id
      }).then(res=>{
        if (res.code == 1) {
          wx.setNavigationBarTitle({
            title: res.data.coupon_info.coupon_title || res.data.coupon_info.goods.goods_name,
          })
          that.setData({
            couponId: res.data.id,
            couponInfo: res.data.coupon_info
          })
        } else {
          wx.showToast({
            title: res.msg,
          })
      }
    })
    wx.hideLoading()
  },
  async getJifenGood (type, id) {  //积分商城兑换品详情
    wx.showLoading({
      title: '请求中',
    })
    let that = this
    await wx.$api.integralGoodsDetail({
        orders_type: type,
        id: id,
        user_id: that.data.user_id
      }).then(item=>{
        if (item.data==null || item.data == [] || !item.data.id) {
          wx.hideLoading()
          let title = type == 1 ? '此商品已下架' : '此优惠券已下架'
          wx.showToast({
            title: title,
            icon: 'none',
            duration:2000,
          })
        } else if (item.code == 1) {
          let navTit = (item.data.goods_name || item.data.coupon_title||'')  + (item.data.spec_name||'')
          wx.setNavigationBarTitle({
            title: navTit||'',
          })
          let VIPLevel = 1
          if (item.data.coupon_user_type_limit == 0) {
            VIPLevel = 0
          } else if (item.data.coupon_user_type_limit == 2) {
            VIPLevel = 4
          } else {
            let level = item.data.vip_name.substr(0, 1)
            if (level == '金') {
              VIPLevel = 2
            } else if (level == '黑') {
              VIPLevel = 3
            }
          }
          let totle = type == 1 ? item.data.goods_integral : item.data.coupon_integral
          that.setData({
            goodsDetail: item.data,
            total: totle,
            VIPLevel: VIPLevel
          })
        } else {
          let title = type == 1 ? '此商品已下架' : '此优惠券已下架'
          wx.showToast({
            title:title,
            icon: 'none'
          })
        }
    })

    wx.hideLoading()
  },
  onChange (e) {
    let goodsNum = e.detail
    // let price = this.data.goodsDetail.goods_integral
    this.setData({
      // total:price*goodsNum
      goodsNum: goodsNum
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var uinfo = wx.getStorageSync('uinfo')
    if (uinfo && uinfo.user) {
      this.setData({
        id: uinfo.user.id,
        userMessage: uinfo.user,
        userlevel: uinfo.user.level
      })
    }
    this.setData({
      goodsNum: 1
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  toUse () {//优惠券兑换商品
    let that = this
    let arr = [
      {
        goods_id: that.data.couponInfo.coupon_exchange_goods,
        number: 1
      }
    ]
    wx.navigateTo({
      url: '/pages/settlement/settlement?coupon_id=' + that.data.couponId + '&goods_info=' + JSON.stringify(arr)
    })
  },
  async toExchange (e) {   //立即兑换
    if (!this.data.goodsDetail || !this.data.goodsDetail.id) {
      let title = this.data.goodType == 1 ? '此商品已下架' : '此优惠券已下架'
      wx.showToast({
        title,
        icon: 'none'
      })
      return
    }
    var that = this
    if (that.data.isRequest == true) return
    that.setData({
      isRequest: true
    })
    wx.showLoading({
      title: '请求中',
    })
    let useScore = that.data.goodsDetail.goods_integral * that.data.goodsNum
    let good_type = that.data.goodsDetail.orders_type
    let good_id = that.data.goodsDetail.id
    let good = that.data.goodsDetail
    let arr = {
      user_id: that.data.userMessage.id,
      number: that.data.goodsNum || 1,
      integral_good_id: good_type == 1 ? good_id : '',
      integral_coupon_id: good_type == 2 ? good_id : '',
      orders_type: that.data.goodsDetail.orders_type,
      notes: ''
    }
    if (!that.data.userMessage) {
      that.setData({
        isRequest: false
      })
      wx.hideLoading()
      wx.navigateTo({
        url: "/pages/register/register"
      })
    } else if (good.coupon_user_type_limit == 1 && that.data.userMessage.is_member != 1) {
      that.setData({
        isRequest: false
      })
      wx.hideLoading()
      Dialog.alert({
        message: '您还未绑定会员 \n 无法兑换',
      }).then(() => {
      })
    } else if (good.status == 0) {
      that.setData({
        isRequest: false
      })
      wx.hideLoading()
      let title = good_type == 1 ? '此商品已下架' : '此优惠券已下架'
      Dialog.alert({
        message: title,
      }).then(() => {
      })
    }
    // else if(good.is_limit==1&&good.surplus_num<1){
    //   that.setData({
    //     isRequest:false
    //   })
    //   wx.hideLoading()
    //   Dialog.alert({
    //     message: '您已超出产品限额， \n 无法兑换',
    //   }).then(() => {
    //   });
    // }else if(good.is_limit==1&&good.surplus_num<that.data.goodsNum){
    //   that.setData({
    //     isRequest:false
    //   })
    //   wx.hideLoading()
    //   let title = '您最多可以再兑换'+good.surplus_num+'件， \n请修改数量'
    //   Dialog.alert({
    //     message: title,
    //   }).then(() => {
    //   });
    // }
    else if (good.coupon_user_type_limit == 2 && that.data.userMessage.is_newUser != 1) {
      that.setData({
        isRequest: false
      })
      wx.hideLoading()
      Dialog.alert({
        message: '仅限于新用户 \n 无法兑换',
      }).then(() => {
      })
    } else if (useScore > that.data.userMessage.score) {
      wx.hideLoading()
      Dialog.alert({
        message: '积分不足 \n 无法兑换',
      }).then(() => { })
      that.setData({
        isRequest: false
      })
    } else {
      if (good_type == 1) {
        wx.hideLoading()
        that.setData({
          isRequest: false
        })
        wx.navigateTo({
          url: "/pages/settlement/settlement?goods_id=" + good_id + "&number=" + that.data.goodsNum + "&orders_type=" + good_type
        })
      } else {
        that.tochange(arr)   //立即兑换
      }
    }
  },
  tochange (arr) {    //立即兑换优惠券
    var that = this
    wx.$api.createIntegralOrder(arr).then(res=>{
        if (res.code == 1) {
          that.setData({
              integral_id:res.data.integral_id,
              // showOK:true,
              // isRequest: false
          })
          that.getUserInfo()
          
        } else {
          that.setData({
            isRequest: false
          })
          wx.hideLoading()
          Dialog.alert({
            message: res.msg,
          }).then(() => { })
        }
    })
  },
  setInfo(){// 订阅消息
    let that = this
    this.setData({
        showOK:false
    })
    return
    let shareData={
      user_id:that.data.userMessage.id,
      type:3,
      other_type:'',
    }
    wx.requestSubscribeMessage({
        tmplIds: that.data.temIds,
        success (res) {
            if(res[that.data.temIds[0]]=='accept'){//同意
               shareData.other_type='1'
            }
            that.sendSetYue(shareData)
        },
        fail(error){
            setTimeout(() => {
                wx.navigateTo({
                    url: '/pages/exchangeDetail/exchangeDetail?id='+that.data.integral_id    //integral_id    兑换详情     orders_id 订单详情
                })
            }, 1200)
          console.log(error,'123失败');
        }
      })
  },
  sendSetYue(data){
      let that = this
    wx.$api.sendTemplate(data).then(res=>{
            if(res.code>0){
            }else{
                wx.showToast({
                  title: res.msg,
                  icon:'none'
                })
            }
            setTimeout(() => {
                wx.navigateTo({
                    url: '/pages/exchangeDetail/exchangeDetail?id='+that.data.integral_id    //integral_id    兑换详情     orders_id 订单详情
                })
            }, 1000)
    })
},
  //获取用用户的积分
  async getUserInfo (integral_id) {
    let that = this
    var userInfo = wx.getStorageSync('uinfo')
    await mode.getUserInfo(userInfo.user.id).then(item => {
      userInfo.user = item.data
      wx.setStorage({ key: 'uinfo', data: userInfo })
      that.setData({
        userMessage: item.data,
        userlevel: item.data.level,
        isRequest: false
      })
      setTimeout(() => {
        wx.navigateTo({
            url: '/pages/exchangeDetail/exchangeDetail?id='+that.data.integral_id    //integral_id    兑换详情     orders_id 订单详情
        })
    }, 1200)
      wx.hideLoading()
    })
  },
  format (time, format) {
    var t = new Date(time)
    var tf = function (i) {
      return (i < 10 ? '0' : '') + i
    }
    return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function (a) {
      switch (a) {
        case 'yyyy':
          return tf(t.getFullYear())
          break
        case 'MM':
          return tf(t.getMonth() + 1)
          break
        case 'mm':
          return tf(t.getMinutes())
          break
        case 'dd':
          return tf(t.getDate())
          break
        case 'HH':
          return tf(t.getHours())
          break
        case 'ss':
          return tf(t.getSeconds())
          break
      }
    })
  },
  randomString: function (n) {
    let str = 'abcdefghijklmnopqrstuvwxyz9876543210'
    let tmp = '',
      i = 0,
      l = str.length
    for (i = 0; i < n; i++) {
      tmp += str.charAt(Math.floor(Math.random() * l))
    }
    return tmp
  }
})